package ifkm.kit.bremodroid;

import java.io.File;
import java.io.PrintStream;

import bremo.main.Bremo;





import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public  class DummySectionFragment extends Fragment {
	/**
	 * The fragment argument representing the section number for this
	 * fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";
	private static final String STATUS = "File is not Ready";
	private static final int REQUEST_CODE = 1;
	private boolean isFileChoosen = false;
	private String fileChoosen = "";
	private TextView status;
	private Button play;
	private Button open;
	private ProgressBar progressBar;
	public EditText errorText;

	
	PrintStream errStream;
	
	public DummySectionFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View rootView = inflater.inflate(R.layout.fragment_main_dummy,
				container, false);
		
		errStream = new PrintStream(System.err) {

			@Override
			public void println(final String s) {
			    rootView.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						errorText.append(s + "\n");
					}
			    	
			    });
				
//				errorText.setCaretPosition(errorText.getDocument().getLength());

			}

			@Override
			public void print(final String s) {
				rootView.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						errorText.append(s + "\n");
					}
			    	
			    });
			}
		};
		
		if (getActivity().findViewById(R.id.pager) != null) {
			
			 status = (TextView) rootView
					.findViewById(R.id.status);
			status.setText(STATUS);
			status.setTextColor(Color.RED);
			status.setClickable(false);
			
			progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);
			progressBar.setVisibility(View.INVISIBLE);
			
			 play = (Button)rootView.findViewById(R.id.play);
			 open = (Button)rootView.findViewById(R.id.open);
			 errorText = (EditText) rootView.findViewById(R.id.editText1);
			
			 play.setEnabled(false);
			
			 play.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					progressBar.setVisibility(View.VISIBLE);
					open.setEnabled(false);
     				mCallback.onStartButtonClicked();
					System.setErr(errStream);
					Bremo bremo = new Bremo(fileChoosen);
					bremo.start();
				 
				    
					Toast.makeText(getActivity(), "test the pressed button", Toast.LENGTH_SHORT).show();
				}
			});
			 
			 
			 open.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
//						File root = new File(Environment.getExternalStorageDirectory().getPath()
//								+ "/Documents/");
//					    Uri uri = Uri.fromFile(root);
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
//					    intent.setDataAndType(uri,"txt/*"); 
						intent.setType("txt/*");
					    intent.addCategory(Intent.CATEGORY_OPENABLE);
					    
					    Log.d("TAG","Intent started");
					    
					    try {
					        startActivityForResult(
					                Intent.createChooser(intent, "Select a File to Open"),
					                REQUEST_CODE);
					        Log.d("TAG", "What wrong??");
					     } catch (android.content.ActivityNotFoundException ex) {
					        //Handle error.
					    	Log.e("ERROR"," Seems not Works");
					    	 Toast.makeText(getActivity(), "Please install a File Manager.", 
					                 Toast.LENGTH_SHORT).show();
					     }
					}
				});
			 
			 Button stop = (Button)rootView.findViewById(R.id.stop);
			 stop.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Toast.makeText(getActivity(), "test the pressed button", Toast.LENGTH_SHORT).show();
					}
				});
		} else {
			errorText = (EditText) rootView.findViewById(R.id.editText1);
		}
		
		
		return rootView;
	}
	
	public void updateView() {
		System.setErr(errStream);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		 if (requestCode == REQUEST_CODE) {
		        if (resultCode == FragmentActivity.RESULT_OK) {
		            Log.d("TAG", "File Uri: " + data.getData().toString());
		           
		            fileChoosen = data.getData().getPath();
		            if (fileChoosen != "") {
		            	isFileChoosen = true;
		            	status.setText("File is Ready");
		    			status.setTextColor(Color.GREEN);
		    			status.setClickable(false);
		    			play.setEnabled(true);
		    			
		            }
		            Log.d("TAG", "File Path: " + fileChoosen);
		        }
		    }
		super.onActivityResult(requestCode, resultCode, data);
	}
	OnButtonClickedListener mCallback;

	    // Container Activity must implement this interface
	    public interface OnButtonClickedListener {
	        public void onStartButtonClicked();
	        public void onStopButtonClicked();
	    }

	    @Override
	    public void onAttach(Activity activity) {
	        super.onAttach(activity);
	        
	        // This makes sure that the container activity has implemented
	        // the callback interface. If not, it throws an exception
	        try {
	            mCallback = (OnButtonClickedListener) activity;
	            Log.d("TAG", "interface on");
	        } catch (ClassCastException e) {
	            throw new ClassCastException(activity.toString()
	                    + " must implement OnButtonClickedListener");
	           
	        }
	    }
	
}